<?php

namespace App\Services\MakeProductComment;

use App\Models\Order;
use App\Models\Product;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class MakeProductCommentRequest extends FormRequest
{
	protected $order;
	
	protected $product;
	
	public function rules()
	{
		return [
			'order_id' => ['required', 'integer', $this->order()],
			'product_id' => ['required', 'integer', $this->product()],
			
			'data' => 'array',
			'data.content' => 'required|string|max:150',
			'data.images' => 'nullable|array',
			'data.is_favor' => 'required',
		];
	}
	
	protected function order()
	{
		return function ($attribute, $value, $fail) {
			
			if (!$order = Order::find($value)) {
				return $fail('目标订单不存在');
			}
			
			if ($order->has_commented) {
				return $fail('目标订单已评价');
			}
			
			$this->order = $order;
			
			return true;
		};
	}
	
	protected function product()
	{
		return function ($attribute, $value, $fail) {
			if (!$product = Product::find($value)) {
				return $fail('目标商品不存在');
			}
			
			$this->product = $product;
			
			return true;
		};
	}
	
	public function getOrder()
	{
		return $this->order;
	}
	
	public function getProduct()
	{
		return $this->product;
	}
}
